import { useMemo, useState, useEffect } from 'react';

interface Props {
    count: number | string;
}

interface Countdown {
    day: string;
    hours: string;
    minutes: string;
    seconds: string;
    isEnd: boolean;
    subTime: number;
}

export const useCountDown = (props: Props) => {
    const { count } = props;
    const [subTime, setSubTime] = useState<number>(Number(count));

    useEffect(() => {
        setSubTime(Number(count));
    }, [count]);

    useEffect(() => {
        const timer = setInterval(() => {
            setSubTime((prevCount) => {
                if (prevCount <= 1000) {
                    clearInterval(timer);
                    return 0;
                }
                return prevCount - 1000;
            });
        }, 1000);

        return () => {
            clearInterval(timer);
        };
    }, [count]);

    return useMemo((): Countdown => {
        const day = Math.floor(subTime / 1000 / 60 / 60 / 24);
        const hours = Math.floor((subTime / 1000 / 60 / 60) % 24);
        const minutes = Math.floor((subTime / 1000 / 60) % 60);
        const seconds = Math.floor((subTime / 1000) % 60);
        const isEnd = subTime <= 1000;

        return {
            day: day < 10 ? `0${day}` : String(day),
            hours: hours < 10 ? `0${hours}` : String(hours),
            minutes: minutes < 10 ? `0${minutes}` : String(minutes),
            seconds: seconds < 10 ? `0${seconds}` : String(seconds),
            isEnd,
            subTime,
        };
    }, [subTime]);
};